<html>
<head>
<meta name = "viewport" content = "initial-scale = 1.0">
<script type="text/javascript" src="json2.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("language", "1");
//http://localhost:8080/gadget/test3.html?up_ss=p49h16NQcZpfmwyON3r6vGQ&up_ws=od6&libs=od6xB-WoatiXJY/lib/libcore.js,4aEaFcUuV9I/lib/libdynamic-height.js,6H4un8xTfDg/lib/libsettitle.js
function getScript(url){
  var scriptTag = document.createElement("script");
  scriptTag.setAttribute("type", "text/javascript");
  scriptTag.setAttribute("src", url);
  document.getElementsByTagName("head")[0].appendChild(scriptTag);
}

var ss ;
var ws ;
var desc;
var site = 'http://'+self.location.host+'/'
var xmlhttp;
var an;
//var ss = 'p49h16NQcZpfmwyON3r6vGQ'
//var ws = 'od6'
var key;
var test;
var test_url ;
var currentmode ;
var item_swapped;

function qs() {
	var qsParm = new Array();
	var query = window.location.search.substring(1);
	var parms = query.split('&');
	for (var i=0; i<parms.length; i++) {
		var pos = parms[i].indexOf('=');
		if (pos > 0) {
			var key = parms[i].substring(0,pos);
			var val = parms[i].substring(pos+1);
			qsParm[key] = val;
		}
	}
	ss = qsParm["up_ss"];
	ws = qsParm["up_ws"];
//	desc = qsParm["up_desc"];
	test_url = site+"json/get/item?ss="+ss+"&ws="+ws;
// servivano per provare a impostare il titolo del gadget ma l'import di libcore.js non fa funzionare + nulla, non so perchè
//	var goglibs = qsParm["libs"].split(',');
//	for (i=0;i<goglibs.length;i++) {
//		getScript("http://www.google.com/ig/f/"+goglibs[i]);
//	} 
} 

function load_item(url){
	xmlhttp=new XMLHttpRequest();
	xmlhttp.onreadystatechange=state_Change;
	xmlhttp.open("GET",url,true);
	xmlhttp.send(null);
//	document.getElementById('question').value=xmlhttp.responseText;
	var a ; 
	a = 1;
}

function state_Change(){
if (xmlhttp.readyState==4)
  {// 4 = "loaded"
  if (xmlhttp.status==200){// 200 = OK
    // ...our code here...
        try{
		test = eval( "(" + xmlhttp.responseText + ")" );
		if (test.e == 'r1') {
			// send to login page
			location.href = site + 'gadget/login.html?continue='+location.href;
		}
		if (test.rand) {  //item swapped by random
			document.getElementById('swapped').innerHTML = '<b>S</b>';
			document.getElementById('swapped').innerHTML = 'S';
			item_swapped = true;
		}
		else {
			document.getElementById('swapped').innerHTML  = '';	
			item_swapped = false;
		}
		title = test.d + ' : ' + test.num[0] + '+' + test.num[1];
		document.title = title;
		document.getElementById('title').firstChild.nodeValue = title;
		toggle_button(true);
		if (test.num[0]+test.num[1]>0) { //there is sth to repeat
			document.getElementById('question').value = test.q;
			an = test.a;
			key = test.k;
			document.getElementById('answer').value = "";
			document.Mioform.showanswer.disabled = false;
			document.Mioform.addbutton.disabled = true;
				document.Mioform.showanswer.focus();
		}
		else{ //no more repetitios
			document.getElementById('question').value = 'NO MORE REPS';
			an=key=document.getElementById('answer').value='';
			document.Mioform.showanswer.disabled = true;
			document.Mioform.addbutton.disabled = false;
			document.Mioform.addbutton.focus();
		}
	}
	catch (err)	{
		// send to login page
		location.href = site + 'gadget/login.html?continue='+location.href;	
	}
//	_IG_SetTitle(title) = test.num[0] + '/' + test.num[1];

  }
  else{
//  alert("Problem retrieving XML data");
  }
}
}

function toggle_button(state)
{
document.Mioform.goodbutton.disabled=document.Mioform.badbutton.disabled=document.Mioform.sosobutton.disabled = state;
if (!state) document.Mioform.goodbutton.focus();

}

function refresh_item()
{
qs();
itemmode();
toggle_button(true);
document.getElementById('question').value=document.getElementById('answer').value = "";
switchitembutton(true);

load_item(test_url)
}

function send(rate){
toggle_button(true);
document.Mioform.showanswer.disabled = true;
	var params = {"q":document.getElementById('question').value,"a":document.getElementById('answer').value,"r":rate,"k":key,"rand":item_swapped};
	var body = JSON.stringify(params);
	var req = new XMLHttpRequest();
	var async = false
	req.open('POST', site+'post/item', async);
	req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	req.setRequestHeader("Content-type", "application/json");
	req.setRequestHeader("Content-length", body.length);
	req.setRequestHeader("Connection", "close");
  if (async) {
    req.onreadystatechange = function() {
      if(req.readyState == 4 && req.status == 200) {
        var response = null;
        try {
         response = eval( "(" + req.responseText + ")" );
        } catch (e) {
         response = req.responseText;
        }
      }
    }
  }
req.send(body);
refresh_item()   	
}
function additem(){
if (document,Mioform.question.value != '' && document,Mioform.answer.value != ''){
	document.Mioform.addbutton.disabled=document.Mioform.refresh.disabled = true;
	var params = {"q":document.getElementById('question').value,"a":document.getElementById('answer').value,"ss":ss,"ws":ws};
	var body = JSON.stringify(params);
	var req = new XMLHttpRequest();
	var async = false
	req.open('POST', site+'add/item/json', async);
	req.setRequestHeader("Content-type", "application/json");
	req.setRequestHeader("Content-length", body.length);
	req.setRequestHeader("Connection", "close");
  if (async) {
    req.onreadystatechange = function() {
      if(req.readyState == 4 && req.status == 200) {
        var response = null;
        try {
         response = eval( "(" + req.responseText + ")" );
        } catch (e) {
         response = req.responseText;
        }
      }
    }
  }
req.send(body);
if (currentmode=='item'){
 	refresh_item();  
}	
else {
	document.Mioform.addbutton.disabled=document.Mioform.refresh.disabled = false;
	clearfields();
}
}
}
function clearfields(){
document.getElementById('question').value = document.getElementById('answer').value = an = key = '';
document.Mioform.addbutton.disabled = false;
document.Mioform.showanswer.disabled = true;
if (currentmode=='add') {
document.getElementById('question').focus();

}
}

function translate (){
//		google.load("language", "1");
		tobetrans = document.getElementById('question').value
		google.language.detect(tobetrans, function(result) {
			var language_dest = 'en';
			if (result.language == 'en') language_dest = 'it';
			google.language.translate(tobetrans, "", language_dest, function(result2) {
				if (!result2.error) document.getElementById('answer').value=result2.translation;
				});
			});	


}
function switchmode(){
	if ( currentmode == 'add'){
		itemmode();
		refresh_item();
	}
	else {
		addmode();
	}
}
function itemmode(){
	currentmode = 'item';
	document.getElementById('mode').innerHTML = 'Add mode';
	switchitembutton(true);


}
function addmode(){
		currentmode = 'add';
		document.getElementById('mode').innerHTML = 'Item mode';
		switchitembutton(false);
		clearfields();


}
function switchitembutton(state){
	if (state) {
		html = '<input disabled="disabled" onclick="toggle_button(false);document.Mioform.answer.value=an" name="showanswer" value="show answer" type="button">';
		html+= '&nbsp; &nbsp;'
		html+= '<b id="swapped"></b>';
		html+= '&nbsp; &nbsp;'
		html+= '<input disabled="disabled" value="Good" name="Level" id="goodbutton" type="button" onclick=send("G")>'
		html+= '&nbsp;';
		html+= '<input disabled="disabled" value="Soso" name="Level" id="sosobutton" type="button" onclick=send("S")>';
		html+= '&nbsp;';
		html+= '<input disabled="disabled" id="badbutton" name="Level" value="Bad" type="button" onclick=send("B")>';
		html+= '<br>';
		html+='<input name="Clear" value="Clear" onclick="clearfields()" type="button">';
		html+='&nbsp;'
		document.getElementById('showbutton').innerHTML = html;
	}
	else document.getElementById('showbutton').innerHTML = '';
}
function swap() {
	var temp = document.getElementById('question').value;
	document.getElementById('question').value=document.getElementById('answer').value;
	document.getElementById('answer').value=temp;
	}
function changecase(){

	convertcase(document.getElementById('question'));
	convertcase(document.getElementById('answer'));
	clearselection () ;
	}
function convertcase(txtarea){	
	var startsel = txtarea.selectionStart;
	var endsel = txtarea.selectionEnd;
	if ( startsel < endsel ) { 
		
		var sl = (txtarea.value).substring(startsel,endsel); 
		var sl2;
		if (/^[A-Z].+/.test(sl))	{
			sl2=sl.toLowerCase();
			}	
		else {
			sl2=sl.toUpperCase();
			}
			
		txtarea.value= (txtarea.value).substring(0,startsel)+sl2+(txtarea.value).substring(endsel);

		}
	}
function clearselection () {
	document.getElementById('question').selectionStart=document.getElementById('question').selectionEnd=0;
	document.getElementById('answer').selectionStart=document.getElementById('answer').selectionEnd=0;
	}

</script>
</head>
<body onload="refresh_item()">
<b id="title"> </b>
<input name="Translate" value="Translate" onclick="translate()" type="button">
<a href="/gadget/index.html">Index</a>
<a id="mode" href="javascript:switchmode()">Add mode</a>
<input name="Case" value="Aa" onclick="changecase()" type="button">
<input name="Swap" value="Swap" onclick="swap()" type="button">
<form name="Mioform"><br>
<textarea  rows="3" name="question" id="question" style="width: 99%;"> ciao</textarea>
<br>
<textarea  rows="3" name="answer" id="answer" style="width: 99%;"></textarea>
<br>
<span id="showbutton">
<!--
<input onclick="toggle_button(false);document.Mioform.answer.value=an" name="showanswer" value="show answer" type="button">
&nbsp; &nbsp;
<input disabled="disabled" value="Good" name="Level" id="goodbutton" type="button" onclick=send("G")>
&nbsp;
<input disabled="disabled" value="Soso" name="Level" id="sosobutton" type="button" onclick=send("S")>
&nbsp;
<input disabled="disabled" id="badbutton" name="Level" value="Bad" type="button" onclick=send("B")>
<br>
<input name="Clear" value="Clear" onclick="clearfields()" type="button">
&nbsp;
-->
</span>
<input disabled="disabled"name="Add" value="Add" id = "addbutton" onclick="key='';additem()" type="button">
<br>
<input name="Refresh" value="Refresh" onclick="refresh_item()" id = "refresh" type="button">
</form>

</body>
</html>
